package com.Lixiaoqian.PartyHistoryMuseum.utils;

import android.media.MediaPlayer;

import java.io.IOException;

/**
 * Created by huangzhibo on 2017/10/12/012.
 * mail:1043202454@qq.com
 */

public class PlayMusic {
    public  MediaPlayer mediaPlayer;
    public int duration;

    public void playMusic(String path) {
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setLooping(true); //循环播放
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            duration = mediaPlayer.getDuration();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pause() { //暂停
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    public void stop() { //暂停
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }

    public void start() { //开始
        if (mediaPlayer!=null&&!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
    }


    /**
     * 时间格式
     *
     * @param time
     * @return
     */
    public String toTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int hour = minute / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    public void onDestory(){
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

}
